package org.rafal.springframework.service.impl;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rafal.springframework.service.FileService;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

@Component("fileService")
public class FileServiceImpl implements FileService {
	private final static Log logger = LogFactory.getLog(FileServiceImpl.class);

	public void saveImage(String filename, MultipartFile image) {

		try {
			File file = new File("c:/tymczasoweFirstAppSpringUpload/resources"
					+ filename);
			logger.info("Saving file to path: " + file.getAbsolutePath());
			FileUtils.writeByteArrayToFile(file, image.getBytes());
			logger.info("File saved sucessfuly.");
		} catch (Exception e) {
			logger.error("Error at saving file");
		}
	}

	public void validateImage(MultipartFile image) {
		logger.info("Validating image: " + image.getName() + ".  File size: "
				+ image.getSize());
		if (!image.getContentType().toString().equals("image/pjpeg")) {
			logger.error("Only JPG images accepted " + image.getContentType().toString());
			//throw new RuntimeException();
		}
		logger.info("Image validation pass.");
		;
	}

}
